package com.deaboway.snake.util;

import java.util.Vector;

import javax.microedition.lcdui.Image;

public class Utils {
	// @J2ME 新增图片缩放方法
	public static final Image zoomImage(Image src, int width, int height) {
		return zoomImage(src, width, height, false);
	}
	
	public static final Image zoomImage(Image src, int width, int height, boolean proRata) {
		if(src==null) return null;
		
		int[] srcBuf = null;
		int[] desBuf = null;
		try{
			int srcW = src.getWidth(); 
			int srcH = src.getHeight(); 

			int desW = width;
			double ratex = (double)srcW /desW;
			int desH = height;
			double ratey = (double)srcH /desH;

			if(proRata){
				if(ratex>=ratey){
					ratey = ratex;
					desH = (int)(srcH/ratex);
				}else{
					ratex = ratey;
					desW = (int)(srcW/ratey);
				}
			}
			if(srcW==desW&&srcH==desH)return src;
			
			srcBuf = new int[srcW * srcH];
			src.getRGB(srcBuf, 0, srcW, 0, 0, srcW, srcH);
			
			src = null;
			System.gc();
			
			int srcY=0,srcX=0,srcrows,destrows = -desW;
			double dsrcY=0,dsrcX=0;
			desBuf = new int[desW * desH];
			for (int destY = 0; destY < desH; ++destY) {
				srcY = (int)(dsrcY + 0.5);
				if(srcY==srcH)srcY--;
				dsrcY += ratey; 
				destrows += desW;
				srcrows = srcY * srcW;
				dsrcX=0;
				for (int destX = 0; destX < desW; ++destX) {
					srcX = (int)(dsrcX + 0.5);
					if(srcX==srcW)srcX--;
					dsrcX += ratex;
					desBuf[destX + destrows] = srcBuf[srcX + srcrows];
				}
			}
			
			return Image.createRGBImage(desBuf, desW, desH, true);
		}catch(Throwable t){
			t.printStackTrace();
			return null;
		} finally{
			srcBuf = null;
			desBuf = null;
			System.gc();
		}
	}
	
	public static final String[] splitUtil(String util, String split) {
		String splits[] = null;
		Vector vector = new Vector();
		int startIndex = 0;
		int index = 0;
		startIndex = util.indexOf(split);
		while (startIndex <= util.length() & startIndex != -1) {
			String temp = util.substring(index, startIndex);
			vector.addElement(temp);
			index = startIndex + split.length();
			startIndex = util.indexOf(split, startIndex + split.length());
		}
		String tail = util.substring(index + 1 - split.length());
		Log.debug("splitUtil:"+tail);
		if(tail!=null&&tail.length()>0)
			vector.addElement(tail);
		splits = new String[vector.size()];
		for (int i = 0; i < splits.length; i++) {
			splits[i] = (String) vector.elementAt(i);
		}
		return splits;
	}
}
